/*
 * MyGWT User Extensions
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.mygwt.ux.client.widgets.table;

import java.util.ArrayList;

import net.mygwt.ui.client.Events;
import net.mygwt.ui.client.Style;
import net.mygwt.ui.client.event.BaseEvent;
import net.mygwt.ui.client.widget.table.EditRowSelectionModel;
import net.mygwt.ui.client.widget.table.EditTableItem;
import net.mygwt.ui.client.widget.table.Table;
import net.mygwt.ui.client.widget.table.TableColumnModel;
import net.mygwt.ui.client.widget.table.TableItem;

import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * @author simon
 *
 */
public class EditTable extends Table {
  ArrayList editors = new ArrayList();
  EditRowSelectionModel selectModel;

  public EditTable(int style, TableColumnModel cm) {
    super(style, cm);

    // Clean up because of super(style, cm)
    removeListener(Events.CellClick, sm);
    removeListener(Events.CellDoubleClick, sm);
    removeListener(Events.KeyDown, sm);
    removeListener(Events.Remove, sm);

    if ((style & Style.MULTI) != 0) {
      sm = new EditRowSelectionModel(Style.MULTI);
    } else {
      sm = new EditRowSelectionModel(Style.SINGLE);
    }

    ((EditRowSelectionModel) sm).init(this);
  }

  public void onBaseEvent(BaseEvent be) {
    TableItem item = findItem(be.getTarget());
    if (item != null) {
      item.onBaseEvent(be);
    }
  }

  public void setEditor(int column, Widget editor) {
    ((EditRowSelectionModel) sm).setEditor(column, editor);
  }

  public void editCurrentRow() {
    EditTableItem item = (EditTableItem) getSelectedItem();
    int row = indexOf(item);
    ((EditRowSelectionModel) sm).openEdit(row, item);
  }

  public void finishEdit() {
    ((EditRowSelectionModel) sm).closeEdit();
  }
}